<template>
    <div class="basic-shape-icon__wrap">
        <n-tooltip v-for="(item, index) in toolText" :key="index" placement="bottom" trigger="hover">
            <template #trigger>
                <span :class="['draw-action_icon',{ 'is-active': activeIndex === index }]" @click.stop="handleAddItem(item, index)">
                    <i :class="[`${item.icon}`]" ></i>
                </span>
            </template>
            <span>{{ item.textTip }}</span>
        </n-tooltip>
    </div>
</template>

<script setup name="TextIcon">
import useSharedCore from "@/hooks/shared";
import { config } from "../config/editor";
import { createShape } from "../utils/createShape";

const { toolText } = config;
const { coverEditor, fabric } = useSharedCore();

let shape = null;
const defOptions = {
    isDrawingLineMode: false,
    lineType: false,
    bgColor: '#18a058',
    lastPt: 1,
    points: [],
    mouseDown: false,
    strokeWidth: 3,
    fill: 'rgba(2, 0, 36, 1)'
}
const state = ref({...defOptions});
const activeIndex = ref(-1)

function handleAddItem(item, index) {
    activeIndex.value = index
    state.value.isDrawingLineMode = ! state.value.isDrawingLineMode;
    
    shape = createShape(item.type, coverEditor.canvas);
    if (shape && coverEditor.canvas) {
        coverEditor.canvas.add(shape);
        coverEditor.canvas.setActiveObject(shape);
        coverEditor.canvas.renderAll();
        // 恢复初始值
        state.value = { ...defOptions }
    }
}

function getActiveObjectAttr(params) {
    if (params && params.length > 0) {
        // 如果已选择图层，需要恢复工具状态
        activeIndex.value = -1
        state.value = { ...defOptions }
    }
}

onMounted(() => {
    // 监听fabric选中更新的selectOne事件
    // selectOne 事件在ServePlugin插件注入的
    coverEditor.on('selectOne', getActiveObjectAttr);
})

onBeforeUnmount(() => {
    coverEditor.off('selectOne', getActiveObjectAttr);
})
</script>

<style lang="scss" scoped>
    .basic-shape-icon__wrap {
        display: flex;
        flex-wrap: wrap;
        .draw-action_icon {
            // flex: 1;
            text-align: center;
            border-radius: 4px;
            transition: color,background 0.1s ease;
            &.is-active {
                color: $activeColor;
                background: $activeBgColor;
            }
            .icon {
                flex: 0 0 50px;
                font-size: 1.5rem;
                cursor: pointer;
                padding: 6px 8px;
            }
        }
    }
</style>
